package ThreadCommunication.pipedstream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * todo 　管道流过程：生产者向管道中输出数据，消费者从管道中读取数据。当然，生产者的管道输出要与消费者的管道输入进行连接。
 * @author dycong
 * @date 2018/5/5 19:16
 */
public class CommunicateWhitPiping {
    public static void main(String[] args) {
        // 创建管道输出流
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        // 创建管道输入流
        PipedInputStream pipedInputStream = new PipedInputStream();
        try {
            // 将管道输入流与输出流连接 此过程也可通过重载的构造函数来实现
            pipedOutputStream.connect(pipedInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建生产者线程
        Producer p = new Producer(pipedOutputStream);
        // 创建消费者线程
        Consumer c = new Consumer(pipedInputStream);
        // 启动线程
        p.start();
        c.start();
    }

   static class Producer extends Thread {
        private PipedOutputStream pos;

        public Producer(PipedOutputStream pos) {
            this.pos = pos;
        }

        public void run() {
            int i = 8;
            try {
                pos.write(i);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 消费者线程(与一个管道输入流相关联)
     */
    static class Consumer extends Thread {
        private PipedInputStream pis;

        public Consumer(PipedInputStream pis) {
            this.pis = pis;
        }

        public void run() {
            try {
                System.out.println(pis.read());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
